package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.LaneApply;
import com.ruoyi.system.domain.LaneKey;
import com.ruoyi.system.domain.SysBaseData;
import com.ruoyi.system.initial.StationMapThread;
import com.ruoyi.system.initial.UserInfoThread;
import com.ruoyi.system.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 数据查询Controller
 *
 * @author lzj
 * @date 2025-04-18
 */
@Controller
@RequestMapping("/system/laneapply")
public class LaneApplyController extends BaseController {
    private final String prefix = "system/laneapply";

    @Autowired
    private ILaneapplyService laneapplyService;

    @Autowired
    private ISysBaseDataService sysBaseDataService;

    @Autowired
    private ILanekeyService lanekeyService;

    @Autowired
    private ISeatcallService seatcallService;

    @Autowired
    private ISeatimageService seatimageService;

    @Autowired
    private UserInfoThread infoThread;

    @Autowired
    private StationMapThread mapThread;

    @RequiresPermissions("system:laneapply:view")
    @GetMapping()
    public String laneapply(ModelMap mmap, LaneApply laneapply) {
        String month = "_" + DateUtils.getCurrentMonthSuffix();
        List<LaneApply> stations = laneapplyService.selectLaneApplyListGroup(month);
        mmap.put("stations", stations);

        SysBaseData sysBaseData = new SysBaseData();
        sysBaseData.setClassId(1L);
        List<SysBaseData> applyTypes = sysBaseDataService.selectSysBaseDataList(sysBaseData);
        mmap.put("applyTypes", applyTypes);

        return prefix + "/laneapply";
    }

    @GetMapping("/getLanesByStation")
    @ResponseBody
    public List<LaneApply> getLanesByStation(@RequestParam String stationHex) {
        String month = "_" + DateUtils.getCurrentMonthSuffix();
        return laneapplyService.selectLanesByStationHex(stationHex, month);
    }

    /**
     * 查询数据查询列表
     */
    @RequiresPermissions("system:laneapply:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(LaneApply laneapply) {
        String tableName;
        Map<String, Object> params = new HashMap<>();
        String time = laneapply.getParams().get("applyTime").toString();
        if (StringUtils.isNotEmpty(time)) {
            tableName = "_" + DateUtils.parseDateToStr("yyyyMM", DateUtils.dateTime("yyyy-MM-dd", time));
            params.put("applyTime", time);
        } else {
            tableName = "_" + DateUtils.getCurrentMonthSuffix();
        }

        params.put("tableName", tableName);
        laneapply.setParams(params);

        // 2. 只查询一次数据库（获取去重后的数据）
        List<LaneApply> list = laneapplyService.selectLaneapplyList(laneapply);
        // 3. 在内存中按tradeId去重（保留第一条记录）
        List<LaneApply> distinctList = list.stream().collect(Collectors.toMap(LaneApply::getTradeId, Function.identity(), (existing, replacement) -> existing // 如果重复，保留已存在的记录
        )).values().stream().collect(Collectors.toList());

        List<String> tradeIds = distinctList.stream().map(LaneApply::getTradeId).distinct().collect(Collectors.toList());

        // 3. 批量查询关联表
        Set<String> keyExists = lanekeyService.getExistingTradeIds(tableName);
        Set<String> callExists = seatcallService.getExistingTradeIds(tableName);
        Set<String> imageExists = seatimageService.getExistingTradeIds(tableName);

        // 4. 使用流式处理统计
        long seatProcessTotal = distinctList.stream().filter(item -> !isOnSiteProcess(item, keyExists, callExists, imageExists)).count();

        startPage();
        List<LaneApply> pageList = laneapplyService.selectLaneapplyList(laneapply);
        // 4. 内存中设置处理方式
        pageList.forEach(item -> {
            item.setApplyTypeName(DictUtils.getDictLabel("sys_base_data", item.getApplyType().toString()));
            item.setUserId(infoThread.getUserInfo(item.getUserId()));
            item.setStationName(mapThread.getStationInfo(item.getStationHex()));
            if (keyExists.contains(item.getTradeId())) {
                item.setProcessingMethod("坐席远控");
            } else if (callExists.contains(item.getTradeId())) {
                item.setProcessingMethod("可视对讲");
            } else if (item.getDealState() == 2L) {
                item.setProcessingMethod("坐席转接");
            } else if (item.getApplyType() == 22L || item.getApplyType() == 23L || item.getApplyType() == 24L || item.getApplyType() == 29L) {
                item.setProcessingMethod("自动处理");
            } else if (imageExists.contains(item.getTradeId()) && item.getApplyType() <= 5) {
                item.setProcessingMethod("坐席识别");
            } else {
                item.setProcessingMethod("现场处理");
            }
        });

        // 将统计结果放入返回数据中
        Map<String, Object> stats = new HashMap<>();
        double seatProcessRatio = Double.parseDouble(distinctList.isEmpty() ? "0.00" : String.format("%.2f", seatProcessTotal * 100.0 / distinctList.size()));
        stats.put("totalCount", list.size());
        stats.put("teQingCount", tradeIds.size());
        stats.put("seatProcessTotal", seatProcessTotal);
        stats.put("seatProcessRatio", seatProcessRatio);

        TableDataInfo rspData = getDataTable(pageList);
        rspData.setStats(stats);
        return rspData;
    }

    // 判断是否为非现场处理（提取为独立方法）
    private boolean isOnSiteProcess(LaneApply item, Set<String> keyExists, Set<String> callExists, Set<String> imageExists) {
        return !(keyExists.contains(item.getTradeId()) || callExists.contains(item.getTradeId()) || item.getDealState() == 2L || isAutoProcessType(item.getApplyType()) || (imageExists.contains(item.getTradeId()) && item.getApplyType() <= 5));
    }

    // 判断是否为自动处理类型（提取为独立方法）
    private boolean isAutoProcessType(Long applyType) {
        return applyType == 22L || applyType == 23L || applyType == 24L || applyType == 29L;
    }

    /**
     * 导出数据查询列表
     */
    @RequiresPermissions("system:laneapply:export")
    @Log(title = "数据查询", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(LaneApply laneapply) {
        String tableName;
        Map<String, Object> params = new HashMap<>();
        String time = laneapply.getParams().get("applyTime").toString();
        if (StringUtils.isNotEmpty(time)) {
            tableName = "_" + DateUtils.parseDateToStr("yyyyMM", DateUtils.dateTime("yyyy-MM-dd", time));
            params.put("applyTime", time);
        } else {
            tableName = "_" + DateUtils.getCurrentMonthSuffix();
        }

        params.put("tableName", tableName);
        laneapply.setParams(params);
        List<LaneApply> list = laneapplyService.selectLaneapplyList(laneapply);
        ExcelUtil<LaneApply> util = new ExcelUtil<LaneApply>(LaneApply.class);
        // 3. 批量查询关联表（4个固定查询）
        Set<String> keyExists = lanekeyService.getExistingTradeIds(tableName);
        Set<String> callExists = seatcallService.getExistingTradeIds(tableName);
        Set<String> imageExists = seatimageService.getExistingTradeIds(tableName);

        // 4. 内存中设置处理方式
        list.forEach(item -> {
            if (keyExists.contains(item.getTradeId())) {
                item.setProcessingMethod("坐席远控");
            } else if (callExists.contains(item.getTradeId())) {
                item.setProcessingMethod("可视对讲");
            } else if (item.getDealState() == 2L) {
                item.setProcessingMethod("坐席转接");
            } else if (item.getApplyType() == 22L || item.getApplyType() == 23L || item.getApplyType() == 24L || item.getApplyType() == 29L) {
                item.setProcessingMethod("自动处理");
            } else if (imageExists.contains(item.getTradeId()) && item.getApplyType() <= 5) {
                item.setProcessingMethod("坐席识别");
            } else {
                item.setProcessingMethod("现场处理");
            }
        });
        return util.exportExcel(list, "数据查询数据");
    }

    /**
     * 新增数据查询
     */
    @RequiresPermissions("system:laneapply:add")
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存数据查询
     */
    @RequiresPermissions("system:laneapply:add")
    @Log(title = "数据查询", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(LaneApply laneapply) {
        return toAjax(laneapplyService.insertLaneapply(laneapply));
    }

    /**
     * 修改数据查询
     */
    @RequiresPermissions("system:laneapply:edit")
    @GetMapping("/edit/{tradeId}")
    public String edit(@PathVariable("tradeId") String tradeId, ModelMap mmap) {
        LaneApply laneapply = laneapplyService.selectLaneapplyByTradeId(tradeId);
        mmap.put("laneapply", laneapply);
        return prefix + "/edit";
    }

    /**
     * 修改保存数据查询
     */
    @RequiresPermissions("system:laneapply:edit")
    @Log(title = "数据查询", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(LaneApply laneapply) {
        return toAjax(laneapplyService.updateLaneapply(laneapply));
    }

    /**
     * 删除数据查询
     */
    @RequiresPermissions("system:laneapply:remove")
    @Log(title = "数据查询", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(laneapplyService.deleteLaneapplyByTradeIds(ids));
    }
}
